package top.spring.study.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.spring.study.dto.Result;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Base64;

@RestController
public class DemoController {

    @RequestMapping("/hello")
    public String hello(){
        System.out.println("hello");
        return "/hello";
    }
    @GetMapping("/testHttpResponse")
    public void testHttpResponse(HttpServletResponse response){
        try (
                InputStream fileInputStream = new FileInputStream("E:\\test.pdf");
                OutputStream outputStream = response.getOutputStream();
                ){

            //设置Http响应头告诉浏览器下载这个附件,下载的文件名也是在这里设置的
            response.setHeader("Content-Disposition", "attachment;filename=" + "test.pdf");
            byte[] bytes = new byte[2048];
            int len = 0;
            while ((len = fileInputStream.read(bytes))>0){
                outputStream.write(bytes,0,len);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

    public static void copyFileUsingFileStreams(File source, File dest) {

        try (
                InputStream input = new FileInputStream(source);
                OutputStream output = new FileOutputStream(dest);
        ) {
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, bytesRead);
            }
        } catch (Exception e) {
            System.out.println("复制文件异常" + e);
        }

    }

    @GetMapping("/testHttpResponse2")
    public Result testHttpResponse2(HttpServletResponse response){
        try{
                InputStream fileInputStream = new FileInputStream("E:\\test2.pdf");
                OutputStream outputStream = response.getOutputStream();


            //设置Http响应头告诉浏览器下载这个附件,下载的文件名也是在这里设置的
            response.setHeader("Content-Disposition", "attachment;filename=" + "test.pdf");
            byte[] bytes = new byte[2048];
            int len = 0;
            while ((len = fileInputStream.read(bytes))>0){
                outputStream.write(bytes,0,len);
            }

            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            return Result.error(2,"失败");
        }

        return Result.ok("成功");
    }
}
